package com.ruoyi.web.util;

import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author ：吉金武
 * @ClassName BasicAuthUtil
 * @date ：2024/5/2 - 21:50
 * @version: V1.0
 * @slogan: 天下风云出我辈，一入代码岁月催
 * @description:
 **/
public class BasicAuthUtil {

    public static String encodeCredentials(String systemName, String companyName) {
        String credentials = systemName + ":" + companyName;
//        byte[] encodedBytes = Base64.getEncoder().encode(credentials.getBytes());
        String encodedAuth =  Base64.getEncoder()
                .encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
        return encodedAuth;
    }

    /**
     * 授权标头添加到HTTP请求
     * @param urlConnection
     * @param username
     * @param password
     */
    public static void addAuthHeader(HttpURLConnection urlConnection, String username, String password) {
        String encodedCredentials = encodeCredentials(username, password);
                urlConnection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
    }

    public static String getBasic(String authorization) {
       if (authorization == null || !authorization.startsWith("Basic ")) {
            return null;
        }
        // Extract Basic credentials
        String encodedCredentials = authorization.substring(6).trim();
        return encodedCredentials;
    }

    public static String[] getBasicUsernameAndPassword(String basic){
        byte[] decodedBytes = Base64.getDecoder().decode(basic);
        String credentials = new String(decodedBytes);

        // Split username and password
        String[] split = credentials.split(":", 2);
        return split;
    }

}

